package com.bbz.core.concurrency.work7;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 原子Integer 操作
 * 
 * @author binbin.a.zhang
 *
 */
public class AtomicDemo {
	private static AtomicInteger atomicInteger = new AtomicInteger(1);
	private static int[] value = new int[] { 1, 2, 3 };
	private static AtomicIntegerArray integerArray = new AtomicIntegerArray(value);
	private static AtomicReference<User> reference = new AtomicReference<>();

	public static void main(String[] args) {
		intger();
		array();
		reference();
	}
	/**
	 * 原子更新基本类型
	 */
	public static void intger() {
		System.out.println(atomicInteger.getAndIncrement());
		System.out.println(atomicInteger.get());
	}
	/**
	 * 原子更新数组类型
	 */
	public static void array() {
		// 对数组中索引为1的位置的元素加5
		int result = integerArray.getAndAdd(1, 5);
		System.out.println(integerArray.get(1));
		System.out.println(result);
	}
	/**
	 * 原子更新引用类型
	 */
	public static void reference() {
		User user1 = new User("a", 1);
		reference.set(user1);
		User user2 = new User("b", 2);
		User user = reference.getAndSet(user2);
		System.out.println(user);
		System.out.println(reference.get());

	}

	static class User {
		private String userName;
		private int age;

		public User(String userName, int age) {
			this.userName = userName;
			this.age = age;
		}

		@Override
		public String toString() {
			return "User{" + "userName='" + userName + '\'' + ", age=" + age + '}';
		}
	}

}
